﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Icoders.MarketTracker.Web.Lib.Command.Orders;
using Icoders.MarketTracker.Web.Lib.Command.Transactions.Orders;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Icoders.MarketTracker.Web.Lib.Command.Helper.Impl
{
    public class CommandDeserialize : ICommandDeserialize
    {
        ICommandValidate _commandValidate;
        public CommandDeserialize(ICommandValidate commandValidate)
        {
            _commandValidate = commandValidate;
        }

        public ICommand DeserializeCommand(string commandType, string jsoncommand)
        {
            CommandType ct = GetCommandType(commandType);
            return DeserializeCommand(ct, jsoncommand);
        }

        private ICommand DeserializeCommand(CommandType ct, string jsoncommand)
        {
            switch (ct)
            {
                    //--------------- Order 
                case CommandType.CreateOrder:
                    CreateOrderCommand oc = null;
                    _commandValidate.CanDeserializeCommand(jsoncommand, out oc);
                    return oc;
                case CommandType.AddOrderLineItem:
                    AddOrderLineItemCommand oac = null;
                    _commandValidate.CanDeserializeCommand(jsoncommand, out oac);
                    return oac;
                case CommandType.ConfirmOrder:
                    ConfirmOrderCommand oco = null;
                    _commandValidate.CanDeserializeCommand(jsoncommand, out oco);
                    return oco;

                default:
                    throw new Exception("Failed to deserialize command in command deserializer");
            }
        }

        public DateTime DeserializeSendDateTime(string sendDateTime)
        {
            DateTime _sendDateTime = DateTime.Now;
            //string d = JsonConvert.SerializeObject(DateTime.Now, new IsoDateTimeConverter()).Replace("\"", "");
            try
            {
                IsoDateTimeConverter converter = new IsoDateTimeConverter();
                string testString = sendDateTime.Replace(" ", "+"); // JsonConvert.SerializeObject(_sendDateTime, new IsoDateTimeConverter());

                DateTimeOffset xx = JsonConvert.DeserializeObject<DateTimeOffset>(testString, converter);

                _sendDateTime = xx.DateTime;// DateTime.Parse(sendDateTime);
            }
            catch
            {
            }

            return _sendDateTime;
        }

        CommandType GetCommandType(string commandType)
        {
            CommandType _commandType;
            Enum.TryParse(commandType, out _commandType);
            return _commandType;
        }
    }
}
